package com.xindaoapp.happypet.activity;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.SecKill;
import com.xindaoapp.happypet.view.CustomDigitalClock;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class SecKillActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;

    @ViewInject(R.id.seckill_list)
    private PullToRefreshListView seckill_list;

    @ViewInject(R.id.iv_status)
    private ImageView iv_status;

    @ViewInject(R.id.tv_status)
    private TextView tv_status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_seckill);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        initListView();
        initTuanData(page);
    }

    private void initListView() {
        seckill_list.setPullRefreshEnabled(false);
        seckill_list.setScrollLoadEnabled(false);

        seckill_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    if (position == 0) {
                        return;
                    } else if (position <= (starting.size())) {
                        starting.get(position - 1).sold_number =
                                (Integer.parseInt(starting.get(position - 1).sold_number) + 1 + "");
                        secAdapter.notifyDataSetChanged();
                        Intent intent =
                                new Intent(SecKillActivity.this, ProductDetailActivity1.class);
                        intent.putExtra("productId", (starting.get(position - 1).goods_id));
                        intent.putExtra("isKill", starting.get(position - 1).isKill);
                        startActivity(intent);
                    } else if (position == starting.size() + 1) {
                        return;
                    } else {
                        willstart.get(position - 1 - starting.size() - 1).sold_number =
                                (Integer.parseInt(willstart.get(position - 1 - starting.size() - 1).sold_number) + 1 + "");
                        secAdapter.notifyDataSetChanged();
                        Intent intent =
                                new Intent(SecKillActivity.this, ProductDetailActivity1.class);
                        intent.putExtra("productId",
                                (willstart.get(position - 1 - starting.size() - 1).goods_id));
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private final int page = 1;
    private SecKillAdapter secAdapter;
    private static List<com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood> starting;
    private static List<com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood> willstart;
    private boolean isFirst = true;

    private void initTuanData(int i) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", Address.PAGECOMMONSIZE);
        /*
         * final ProgressHUD progressHUD = ProgressHUD.show(SecKillActivity.this, "正在加载...", true,
         * true, null);
         */
        AddClient.get(Address.SECKILL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    isFirst = false;
                    onDataArrived(true);
                    SecKill parse = JSON.parseObject(content, SecKill.class);
                    if (parse.getStatus().equals("1")) {
                        starting = parse.data.starting;
                        willstart = parse.data.willStart;
                        if (secAdapter == null) {
                            secAdapter = new SecKillAdapter();
                            seckill_list.getRefreshableView().setAdapter(secAdapter);
                        } else {
                            secAdapter.notifyDataSetChanged();
                        }
                        seckill_list.getRefreshableView().setOnScrollListener(
                                new OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(AbsListView view,
                                            int scrollState) {
                                        // TODO Auto-generated method stub

                                    }

                                    @Override
                                    public void onScroll(AbsListView view, int firstVisibleItem,
                                            int visibleItemCount, int totalItemCount) {
                                        if (firstVisibleItem > starting.size()) {
                                            iv_status.setImageDrawable(getResources().getDrawable(
                                                    R.drawable.tuan_time_img));
                                            tv_status.setText("即将开始");
                                        } else {
                                            iv_status.setImageDrawable(getResources().getDrawable(
                                                    R.drawable.shalou));
                                            tv_status.setText("抢购中");
                                        }
                                    }
                                });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            initTuanData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });

    }

    private class SecKillAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return 1 + starting.size() + 1 + willstart.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood info;
            if (position == 0) {
                RelativeLayout ll =
                        (RelativeLayout) View.inflate(SecKillActivity.this, R.layout.seckill_top,
                                null);
                ImageView iv = (ImageView) ll.findViewById(R.id.iv_status);
                TextView tv = (TextView) ll.findViewById(R.id.tv_status);
                iv.setImageDrawable(getResources().getDrawable(R.drawable.shalou));
                tv.setText("抢购中");
                return ll;
            } else if (position == (starting.size() + 1)) {
                RelativeLayout ll =
                        (RelativeLayout) View.inflate(SecKillActivity.this, R.layout.seckill_top,
                                null);
                ImageView iv = (ImageView) ll.findViewById(R.id.iv_status);
                TextView tv = (TextView) ll.findViewById(R.id.tv_status);
                iv.setImageDrawable(getResources().getDrawable(R.drawable.tuan_time_img));
                tv.setText("即将开始");
                return ll;
            } else if (position <= starting.size()) {
                info = starting.get(position - 1);
            } else {
                info = willstart.get(position - 1 - starting.size() - 1);
            }
            View view;
            ViewHolder holder;
            if (convertView != null && convertView instanceof LinearLayout) {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            } else {
                view = View.inflate(SecKillActivity.this, R.layout.good_seckill_item, null);
                holder = new ViewHolder();
                holder.good_pic = (ImageView) view.findViewById(R.id.good_pic);
                holder.good_name = (TextView) view.findViewById(R.id.good_name);
                holder.good_shop_price = (TextView) view.findViewById(R.id.good_shop_price);
                holder.good_market_price = (TextView) view.findViewById(R.id.good_market_price);
                holder.good_sell = (TextView) view.findViewById(R.id.good_sell);
                holder.good_surplus = (TextView) view.findViewById(R.id.good_surplus);
                holder.good_dazhe = (TextView) view.findViewById(R.id.good_dazhe);
                holder.seckill_status = (TextView) view.findViewById(R.id.seckill_status);
                holder.goods_comment = (TextView) view.findViewById(R.id.goods_comment);
                holder.seckill_time = (CustomDigitalClock) view.findViewById(R.id.seckill_time);
                view.setTag(holder);
            }
            holder.good_name.setText(info.goods_name);
            holder.good_shop_price.setText(formatPrice(Float.valueOf(info.ext_infos.price_ladder
                    .get(0).price)));
            holder.good_market_price.setText("￥" + formatPrice(Float.valueOf(info.market_price)));
            holder.good_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.good_sell.setText(info.sold_number);
            holder.good_surplus.setText(info.goods_number);
            holder.goods_comment.setText(info.comment_percent);

            float a =
                    (Float.valueOf(info.ext_infos.price_ladder.get(0).price) / Float
                            .valueOf(info.market_price)) * 10;
            holder.good_dazhe.setText(formatDaZhe(a) + "折");



            if ((formatDate(info.start_time) - System.currentTimeMillis()) < 0) {
                holder.seckill_status.setText("距离结束");
                holder.seckill_time.setEndTime((formatDate(info.end_time)));
                if ((formatDate(info.end_time) - System.currentTimeMillis()) < 0) {
                    // starting.remove(position+1);
                    // secAdapter.notifyDataSetChanged();
                    holder.good_shop_price.setText(formatPrice(Float.valueOf(info.shop_price)));
                    starting.get(position - 1).isKill = "0";
                    holder.seckill_status.setText("已结束");
                }
            } else if ((formatDate(info.start_time) - System.currentTimeMillis()) > 0) {
                holder.seckill_status.setText("即将开始");
                holder.seckill_time.setEndTime((formatDate(info.start_time)));
            } else if ((formatDate(info.end_time) - System.currentTimeMillis()) < 0) {
                holder.seckill_status.setText("秒杀结束");
            }
            ImageLoader.getInstance().displayImage(info.goods_thumb, holder.good_pic);
            return view;
        }
    }

    private String formatDaZhe(Float a) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(a);
    }

    private String formatPrice(Float a) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(a);
    }

    class ViewHolder {
        ImageView good_pic;
        TextView good_name;
        TextView good_shop_price;
        TextView good_market_price;
        TextView good_sell;
        TextView good_surplus;
        TextView good_dazhe;
        TextView seckill_status;
        TextView goods_comment;
        CustomDigitalClock seckill_time;
    }

    public static long formatDate(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void initClick() {
        tittle_shop_cancel.setOnClickListener(this);
        tittle_shop_content.setText("尾巴圈秒杀");

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (null != willstart && willstart.size() > 0) {
            willstart.clear();
        }
        if (null != starting && starting.size() > 0) {
            starting.clear();
        }
        super.onDestroy();
    }

}
